<template>
  <el-dialog
    v-el-drag-dialog
    class="showDialog"
    :title="title"
    :visible="visible"
    width="1000px"
    append-to-body
    :close-on-click-modal="false"
    @update:visible="updateVisible"
    :destroy-on-close="true"
  >
    <div v-if="self_form" class="show-box">
      <!-- 基本信息区 -->
      <div class="left">
        <div class="info-row">
          <div class="show-name-input">
            <span>{{ $t('发布名称') }}</span>
            <el-input
              style="width: 430px"
              v-model="self_form.name"
              clearable
              maxlength="20"
              :show-word-limit="false"
            ></el-input>
          </div>
          <el-button @click="okClick" type="primary" size="small">{{
            $t('确定')
          }}</el-button>
          <el-button
            @click="cancelClick"
            style="margin-left: 19px"
            size="small"
            >{{ $t('取消') }}</el-button
          >
        </div>
        <!-- 视图或列表显示区 -->
        <div class="show-panel">
          <el-tabs
            style="height: 50px; border-bottom: none"
            v-model="tabName"
            type="border-card"
          >
            <el-tab-pane :label="$t('视图显示')" name="first"></el-tab-pane>
            <el-tab-pane :label="$t('列表显示')" name="second"></el-tab-pane>
          </el-tabs>
          <!-- 替换为视图组件 -->
          <div v-show="tabName === 'first'" style="height: 490px">
            <!-- <calendar-table :data="self_form.programSchedulePlay"></calendar-table> -->
            <time-view
              :list="timeViewList"
              :limit-times="timeLimits"
            ></time-view>
          </div>
          <div style="padding: 0 10px 10px 10px;">
            <list
              height="485px"
              v-show="tabName === 'second'"
              row-key="_id"
              :list-data="listData"
              style="margin: 6px 0"
              :list-cols="listCols"
              :action-opts="actionOpts"
            >
            </list>
          </div>
        </div>
      </div>
      <!-- 属性区 -->
      <div class="right">
        <div class="info-row attr-title">
          {{ $t('属性') }}
        </div>
        <div>
          <plant-form :form="self_form">
            <el-form-item :label="$t('列表')">
              <div style="text-align: right">
                <el-button @click="_openEdit" type="primary">{{
                  $t('编辑')
                }}</el-button>
              </div>
            </el-form-item>
            <list
              height="146px"
              row-key="_id"
              :list-data="listData2"
              :list-cols="listCols2"
              :action-opts="actionOpts2"
            ></list>
          </plant-form>
        </div>
      </div>
    </div>

    <list-edit-dialog
      v-if="self_form"
      :list.sync="self_form.programSchedulePlay"
      :visible.sync="editDialog.show"
    ></list-edit-dialog>
  </el-dialog>
</template>

<script>
import List from '@/components/List'
import PlantForm from './Form/plantForm'
import ListEditDialog from './ListEditDialog'
// import CalendarTable from '@/components/CalendarTable'
import TimeView from './TimeView'

export default {
  components: {
    TimeView,
    List,
    PlantForm,
    ListEditDialog,
    // CalendarTable
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    opType: {
      type: String,
      default: '1',
    },
    form: {
      type: Object,
      default() {
        return null
      },
    },
  },
  watch: {
    form: {
      immediate: true,
      handler(v) {
        if (!v) {
          this.self_form = null
        } else {
          this.self_form = v
        }
      },
    },
  },

  data() {
    const headerContextMenus = {
      items: ['sortUp', 'sortDown'],
    }
    return {
      self_form: null,
      editDialog: {
        show: false,
      },
      showName: '',
      tabName: 'first',
      // 视图区的列表数据
      listCols: [
        { label: '开始时间', prop: 'startTime', headerContextMenus },
        { label: '结束时间', prop: 'endTime', headerContextMenus },
        { label: '发布类型', prop: 'priority', headerContextMenus },
        { label: '节目', prop: 'programName', headerContextMenus },
      ],
      actionOpts: { show: false },
      // 属性区的列表数据
      listCols2: [
        { label: '开始时间', prop: 'startTime', minwidth: 90 },
        { label: '结束时间', prop: 'endTime', minwidth: 90 },
        { label: '节目', prop: 'programName', minwidth: 100 },
      ],
      actionOpts2: { show: false },
      self_listDataId: 1,
      self_listData2Id: 1,
    }
  },
  computed: {
    title() {
      return this.opType === '1'
        ? this.$t('添加发布计划')
        : this.$t('编辑发布计划')
    },
    timeLimits() {
      const { startDate, endDate, week } = this.self_form
      return {
        startDate,
        endDate,
        week,
      }
    },
    timeViewList() {
      // 时间视图列表
      const priorityName = ['缺省', '普通', '优先', '急迫']
      if (
        this.self_form &&
        this.self_form.programSchedulePlay &&
        this.self_form.programSchedulePlay.length > 0
      ) {
        let _list = []
          .concat(this.self_form.programSchedulePlay)
          .map((item) => {
            return {
              ...item,
              priority: this.$t(priorityName[item.priority]),
            }
          })
        return _list
      } else {
        return []
      }
    },
    listData() {
      // 左视图列表
      const priorityName = ['缺省', '普通', '优先', '急迫']
      if (
        this.self_form &&
        this.self_form.programSchedulePlay &&
        this.self_form.programSchedulePlay.length > 0
      ) {
        let _list = []
          .concat(this.self_form.programSchedulePlay)
          .map((item) => {
            return {
              ...item,
              priority: this.$t(priorityName[item.priority]),
            }
          })
        return this.list2treeList(
          _list,
          ['startTime', 'endTime', 'priority'],
          'startTime'
        )
      } else {
        return []
      }
    },
    listData2() {
      // 右下列表
      if (
        this.self_form &&
        this.self_form.programSchedulePlay &&
        this.self_form.programSchedulePlay.length > 0
      ) {
        let _list = [].concat(this.self_form.programSchedulePlay)
        return this.list2treeList(_list, ['startTime', 'endTime'], 'startTime')
      } else {
        return []
      }
    },
  },
  methods: {
    list2treeList(list, treePropLevelArr, firstProp) {
      let _id = 1 // 用于生成树的key
      function _genTree(currProp, data) {
        const currPropIndex = treePropLevelArr.indexOf(currProp)
        const _o = {}
        _o._id = _id++
        _o[firstProp] = data[currProp]
        _o.children = []
        if (
          treePropLevelArr.indexOf(currProp) ===
          treePropLevelArr.length - 1
        ) {
          // 最后一个
          _o.children.push({
            _id: _id++,
            ...data,
          })
        } else {
          _o.children.push(_genTree(treePropLevelArr[currPropIndex + 1], data))
        }
        return _o
      }

      return list.reduce((arr, item) => {
        let sameItemMap = Array(treePropLevelArr.length)
        for (let index = 0; index < treePropLevelArr.length; index++) {
          // 按treePropLevelArr进行比对
          if (index === 0) {
            // 第一位在arr第一层找且对比firstProp
            sameItemMap[index] = arr.find(
              (i) => i[firstProp] === item[firstProp]
            )
          } else {
            // 否则跟前一值作比对
            sameItemMap[index] = sameItemMap[index - 1].children.find(
              (i) => i[firstProp] === item[treePropLevelArr[index]]
            )
          }

          if (!sameItemMap[index]) {
            // 没找到就以自身创建树
            if (index === 0) {
              arr.push(_genTree(treePropLevelArr[index], item))
            } else {
              sameItemMap[index - 1].children.push(
                _genTree(treePropLevelArr[index], item)
              )
            }
            return arr // 跳出此项循环
          } else {
            if (index !== treePropLevelArr.length - 1) {
              // 如果不是最后一层对比则进入下一层对比
              continue
            } else {
              // 最后一项也匹配正确就直接推入
              sameItemMap[index].children.push({
                _id: _id++,
                ...item,
              })
              return arr // 跳出循环
            }
          }
        }
      }, [])
    },
    updateVisible(v) {
      this.$emit('update:visible', v)
    },
    okClick(v) {
      if (this.valiForm()) {
        this.fetching = true
        if (this.opType === '1') {
          this.$emit('addClick', this.self_form, this.fetchingEndCb)
        } else if (this.opType === '2') {
          this.$emit('updateClick', this.self_form, this.fetchingEndCb)
        } else {
          this.updateVisible(false)
        }
      }
    },
    valiForm() {
      // 校验表单
      // 验证是否有节目
      if (this.self_form.programSchedulePlay.length < 1) {
        this.$message.error('节目列表为空')
        return false
      }
      if (!this.self_form.name) {
        this.$message.error('请输入名称')
        return false
      }
      return true
    },
    preClick() {},
    fetchingEndCb(stopClose) {
      this.fetching = false
      !stopClose && this.updateVisible(false)
    },
    cancelClick() {
      this.updateVisible(false)
    },
    _openEdit() {
      this.editDialog = {
        ...this.editDialog,
        show: true,
      }
    },
  },
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';

$info-row-h: 57px;
$border-style: 1px solid $bg-e9;

.showDialog {

  ::v-deep .el-dialog__body {
    padding: 0 !important;
  }

  ::v-deep .el-dialog__header {
    border-bottom: $border-style;
  }


  ::v-deep .time-view {
    .main {
      .time-view-table {
        display: inline-block;
        border: 1px solid #e3e3e3;
        margin-right: 10px !important;
        &.hasYItems{
          width: calc(100% - 70px) !important;
        }
        .y-line {
          position: absolute;
          top: 0;
          border-right: 1px dashed #e3e3e3;
        }
        .table-row + .table-row {
          border-top: 1px dashed #e3e3e3;
        }

      }
    }
  }
}

.show-box {
  display: flex;
  align-items: stretch;

  .left {
    flex: 1;
    padding: 0 20px 20px 20px;
    .info-row {
      height: $info-row-h;
      display: flex;
      align-items: center;
      height: 57px;

      .show-name-input {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 500px;
        margin-right: 21px;
      }
    }

    .show-panel {
      width: 680px;
      height: 550px;
      border: $border-style;
    }
  }

  .right {
    width: 280px;
    border-left: $border-style;

    .attr-title {
      background: $bg-f9;
      border-bottom: $border-style;
      padding-left: 15px;
      line-height: 48px;
      font-size: $font-size-16;
      color: $bg-33;
    }

    .element-name {
      font-size: $font-size-14;
      color: $bg-33;
      padding-left: 20px;
      height: 44px;
      line-height: 44px;
      border-bottom: $border-style;
    }
  }
} 
</style>